package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 1. 构建日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 2. 构建营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // *. 将日期转换为时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // *. 将查询条件封装
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            // 2.1. 调用mapper查询
            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null) {
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }

        // 3. 封装Vo
        // 将集合的所有元素取出来，用逗号隔开
        // 例如：2022-10-01,2022-10-02,2022-10-03
        // 例如：406.0,1520.0,75.0
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1. 构建日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 2. 构建用户总量集合
        List<Integer> totalUserList = new ArrayList<>();

        // 3. 构建新增用户总量集合
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            // *. 将日期转换为时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // *. 将查询条件封装
            Map<String, Object> map = new HashMap<>();
            map.put("endTime", endTime);
            // 2.1. 调用mapper查询用户总量
            Integer totalUser = userMapper.countByMap(map);
            if (totalUser == null) {
                totalUser = 0;
            }
            totalUserList.add(totalUser);
            map.put("beginTime", beginTime);
            // 3.1. 调用mapper查询新增用户量
            Integer newUser = userMapper.countByMap(map);
            if (newUser == null) {
                newUser = 0;
            }
            newUserList.add(newUser);
        }

        // 4. 封装Vo
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 1. 构建日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 2. 构建每日订单数集合
        List<Integer> orderCountList = new ArrayList<>();

        // 3. 构建每日有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            // *. 将日期转换为时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // *. 将查询条件封装
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            // 2.1. 调用mapper查询订单总数
            Integer orderCount = orderMapper.countByMap(map);
            if (orderCount == null) {
                orderCount = 0;
            }
            orderCountList.add(orderCount);
            // 3.1. 调用mapper查询有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            if (validOrderCount == null) {
                validOrderCount = 0;
            }
            validOrderCountList.add(validOrderCount);
        }

        // 4. 构建订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        // 5. 构建有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        // 6. 构建订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount > 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        // 7. 封装Vo
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 1. 将日期转换为时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 2. 将查询条件封装
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);

        // 3. 调用mapper查询Top10商品
        List<GoodsSalesDTO> salesTop10 = orderMapper.top10ByMap(map);

        // 4. 构建商品名称列表
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        // 5. 构建商品销售量列表
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        // 6. 封装Vo
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 导出Excel报表
     *
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        // 1. 查询数据近30天
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now();
        // 1.1. 调用service查询概览数据
        BusinessDataVO businessDataVO = workspaceService.businessData(begin.atTime(LocalTime.MIN), end.atTime(LocalTime.MAX));

        // 2. 通过POI导出Excel报表
        // 2.1. 从类路径获取
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 2.2. 创建Excel工作簿
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 2.3. 获取工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            // 2.3.1 填充数据 时间
            sheet.getRow(1).getCell(1).setCellValue("时间" + begin + "至" + end);

            // 2.4. 填充概览数据
            // 2.4.2. 填充数据 营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            // 2.4.3. 填充数据 有效订单数
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            // 2.4.4. 填充数据 订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            // 2.4.5. 填充数据 平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            // 2.4.6. 填充数据 新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());

            // 2.5. 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessData = workspaceService.businessData(date.atTime(LocalTime.MIN), date.atTime(LocalTime.MAX));
                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3. 通过输出流对象将Excel文件输出到客户端浏览器
            OutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            // 4. 关闭流
            outputStream.close();
            excel.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
